﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data;
using System.Web;

namespace logic
{
    public class customer
    {
        public static int userId
        {
            get
            {
                int tempId;
                try { tempId = Convert.ToInt32(HttpContext.Current.Session["psloginid"]); }
                catch { tempId = 0; }
                if (0 == tempId)
                    try { tempId = Convert.ToInt32(Library.StringLbl.EncryptRc2Decrypt(cookLoinId.Values["psloginid"])); }
                    catch { tempId = 0; }
                return tempId;

            }
            set { System.Web.HttpContext.Current.Session["psloginid"] = value; }
        }

        public static int companyId
        {
            get
            {
                int tempId;
                try
                {
                    tempId = Convert.ToInt32(HttpContext.Current.Session["psCompanyId"]);
                }
                catch 
                { 
                    tempId = 0; 
                }
                if (0 == tempId)
                {
                    try
                    {
                        tempId = Convert.ToInt32(Library.StringLbl.EncryptRc2Decrypt(cookLoinId.Values["psCompanyId"]));
                    }
                    catch { tempId = 0; }
                }

                if (tempId==0)
                {
                    tempId = logic.customer.getCompanyId();
                }

                return tempId;

            }
            set { System.Web.HttpContext.Current.Session["psCompanyId"] = value; }
        }

        static HttpCookie cookLoinId
        {
            get
            {
                return HttpContext.Current.Request.Cookies["psInfor"];
            }
        }

        public static void logout()
        {
            HttpContext.Current.Response.Cookies["psInfor"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Session.Remove("psloginid");
            HttpContext.Current.Session.Remove("psCompanyId");
            HttpContext.Current.Response.Redirect("/login.html");
        }

        public static void insert(CustomerEntity cus)
        {
            Customer.insert(cus);
        }

        public static void update(CustomerEntity cus)
        {
            Customer.update(cus);
        }


        public static void delete(int customerId)
        {
            Customer.delete(customerId);
        }

        public static CustomerEntity getById(int customerId)
        {           
            return Customer.getById(customerId);
        }

        public static DataSet select(string where, string orderby, int pagesize, int pageindex)
        {
            return DAL.DbHelper.ExecuteDataSetPageSize("*", "vw_Customer_list", where, "customerId", orderby, pagesize, pageindex);
        }

        public static CustomerEntity login(string username, string password)
        {
            return Customer.login(username, password);
        }
        string msg = "";
        private bool ValidateCode(string validateCode)
        {
            
            if (HttpContext.Current.Request.Browser.Cookies)
            {
                if (HttpContext.Current.Request.Cookies["CheckCode"] == null)
                {
                    msg = "3";
                    return false;
                }
                else
                {
                    if (String.Compare(HttpContext.Current.Request.Cookies["CheckCode"].Value, validateCode, true) != 0)
                    {

                        msg = "4";
                        return false;
                    }
                }
                return true;
            }
            else
            {
                msg = "5";
                return false;
            }
        }
        protected void checkinfo()
        {
            string username = HttpContext.Current.Request.QueryString["username"].ToString();
            string password = HttpContext.Current.Request.QueryString["password"].ToString();
            string validateCode = HttpContext.Current.Request.QueryString["validateCode"].ToString();
            bool chkrm = Convert.ToBoolean(HttpContext.Current.Request.QueryString["chkrememberme"].ToString());
            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
            {
                if (ValidateCode(validateCode))
                {
                    DAL.CustomerEntity cusomter = logic.customer.login(username, Library.StringLbl.EncryptMD5(password));
                    if (cusomter.CustomerId != 0)
                    {
                        logic.customer.RecordLogin(cusomter.CustomerId, cusomter.CompanyId, chkrm);

                        //if (passWord == ConfigurationManager.AppSettings["InitPassword"])
                        //{
                        //    string passwordCUrl = string.Format("firstpwdEdit.html?customid={0}", ToBase64(Library.StringLbl.EncryptRc2(cusomter.CustomerId.ToString())));
                        //    Response.Redirect(passwordCUrl, true);
                        //}

                        logic.loginLog.insertFade(cusomter.CustomerId, "2", System.Web.HttpContext.Current.Session.SessionID);
                        msg = "1";
                        HttpContext.Current.Response.Write(msg);
                        HttpContext.Current.Response.End();
                    }
                    else
                    {
                        msg = "2";
                        HttpContext.Current.Response.Write(msg);
                        HttpContext.Current.Response.End();
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write(msg);
                    HttpContext.Current.Response.End();
                }
            }

        }
        public static void updatePwd(CustomerEntity cus)
        {
            Customer.updatePwd(cus);
        }
        public static bool isExistUser(string username)
        {
            return Customer.isExistUser(username);
        }
        public static void RecordLogin(int id,int _companyId,bool remember)
        {
            userId = id;
            companyId = _companyId;
            if (remember)
            {
                HttpCookie cookie = new HttpCookie("psInfor");
                cookie.Values["psloginid"] = Library.StringLbl.EncryptRc2(userId.ToString());
                cookie.Values["psCompanyId"] = Library.StringLbl.EncryptRc2(companyId.ToString());

                int defaultDay = 1;
                int.TryParse(System.Configuration.ConfigurationManager.AppSettings["CookieExpiresDay"],out defaultDay);
                cookie.Expires = DateTime.Now.AddDays(defaultDay);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
        public static int getCompanyId()
        {
            return logic.customer.getById(userId).CompanyId;
        }

        public static DataRow getByUsername(string username)
        {
            return Customer.getByUsername(username);
        }
        public static bool isAdmin()
        {
            return logic.customer.getById(userId).IsAdmin;
        }

        /// <summary>
        /// 用户是否可以进入页面
        /// </summary>
        /// <param name="powers">页面权限</param>
        /// <returns></returns>
        public static bool allowAccess(string powers)
        {
            return Customer.allowAccess(userId, powers);
        }

        public static void updatePermission(int cusId, string permission)
        {
            Customer.updatePermission(cusId, permission);
        }

        public static void updatePwdByadmin(int customerid, string password,int adminid,string loginIp)
        {
            Customer.updatePwdByadmin(customerid, password,adminid,loginIp);
        }
    }
}
